package com.itzxx.huazhun.ui.record.curve

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartModel
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartType
import com.github.aachartmodel.aainfographics.aachartcreator.AASeriesElement
import com.itzxx.huazhun.R
import com.itzxx.huazhun.data.model.DevicesChildBean
import com.itzxx.huazhun.data.model.EventMessage
import com.itzxx.huazhun.data.model.EventType
import com.itzxx.huazhun.databinding.ActivityCurveAnalysisBinding
import com.itzxx.huazhun.ui.device.DevicesAdapter
import com.itzxx.huazhun.ui.record.detail.RecordDetailActivity
import com.itzxx.huazhun.view.adapter.CustomLoadMoreAdapter
import com.itzxx.library_base_ktx.base.activity.BaseVmDbActivity
import com.itzxx.library_base_ktx.ext.view.addLinearAdapter
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CurveAnalysisActivity :
    BaseVmDbActivity<CurveAnalysislViewModel, ActivityCurveAnalysisBinding>() {

    companion object {
        fun startActivity(context: Context, id: String) {
            val instent = Intent(
                context,
                CurveAnalysisActivity()::class.java
            )
            instent.putExtra("recordId", id)
            context.startActivity(
                instent
            )
        }

        fun startActivity(context: Context, deviceId: Int,recordId:String,equipmentNo:String?) {
            val instent = Intent(
                context,
                CurveAnalysisActivity()::class.java
            )
            instent.putExtra("recordId", recordId)
            equipmentNo?.let {
                instent.putExtra("deviceId", deviceId)
                instent.putExtra("equipmentNo", equipmentNo)
            }
            context.startActivity(
                instent
            )
        }
    }

    lateinit var aaChartModel: AAChartModel
    private lateinit var curveDataListAdapter: CurveDataListAdapter
    private lateinit var helper: QuickAdapterHelper
    private lateinit var loadMoreAdapter: CustomLoadMoreAdapter

    override fun initView(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        setSupportActionBar(mDatabind.tbHead)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        aaChartModel = AAChartModel()
            .chartType(AAChartType.Line)
            .backgroundColor("#ffffff")
            .dataLabelsEnabled(false)
            .legendEnabled(false)
            .yAxisTitle("")
        initRecyclerView()
        mViewModel.queryEquipmentDataCurve(intent.getStringExtra("recordId")!!)
        mViewModel.requestDetail(
            intent.getIntExtra("deviceId", 0),
            intent.getStringExtra("equipmentNo")
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun createObserver() {
        mViewModel.run {
            curveDataLiveData.observe(this@CurveAnalysisActivity) {
                aaChartModel.series(it.toArray())
                mDatabind.aaChartView.aa_drawChartWithChartModel(aaChartModel)
            }

            curveDataCategoriesLiveData.observe(this@CurveAnalysisActivity) {
                aaChartModel.categories(it.toTypedArray())
                mDatabind.aaChartView.aa_drawChartWithChartModel(aaChartModel)
            }

            listDataUiStateLiveData.observe(this@CurveAnalysisActivity) {
                if (it.isRefresh) {
                    if (it.listData.isNotEmpty()){
                        mDatabind.tvQiya.text = it.listData[0].detailed[0].name
                        if (it.listData[0].detailed.size>1){
                            mDatabind.tvWendu.visibility = View.VISIBLE
                            mDatabind.lineWendu.visibility = View.VISIBLE
                            mDatabind.tvWendu.text = it.listData[0].detailed[1].name
                        }
                    }
                    curveDataListAdapter.submitList(it.listData)
                } else {
                    curveDataListAdapter.addAll(it.listData)
                }

                if (it.hasMore) {
                    helper.trailingLoadState = LoadState.NotLoading(false)
                } else {
                    loadMoreAdapter.setFirstNotFullScreen(it.isRefresh)
                    helper.trailingLoadState = LoadState.NotLoading(true)
                }
            }
        }
    }

    private fun initRecyclerView() {
        curveDataListAdapter = CurveDataListAdapter()
        loadMoreAdapter = CustomLoadMoreAdapter()
        loadMoreAdapter.setOnLoadMoreListener(object : TrailingLoadStateAdapter.OnTrailingListener {
            override fun onLoad() {
                // 执行加载更多的操作，通常都是网络请求
                mViewModel.queryEquipmentDataCurve(false)
            }

            override fun onFailRetry() {
                // 加载失败后，点击重试的操作，通常都是网络请求
                mViewModel.queryEquipmentDataCurve(false)
            }

            override fun isAllowLoading(): Boolean {
                return true
            }
        })
        helper = QuickAdapterHelper.Builder(curveDataListAdapter)
            .setTrailingLoadStateAdapter(loadMoreAdapter)
            .build()
        helper.trailingLoadState = LoadState.None
        mDatabind.rvList.addLinearAdapter(helper.adapter)
    }

    override fun databind2ViewModel() {
        super.databind2ViewModel()
        mDatabind.viewmodel = mViewModel
    }

    override fun isApplyDefaultWaitDialog(): Boolean {
        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        finish()
        return true
    }

    //接收事件
    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    fun onReceiveMsg(message: EventMessage) {
        if (EventType.UPLOAD_RECORD == message.type) {
            mViewModel.requestDetail(message.arg1.toInt(),message.arg2)
        }
    }
}